﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bird.Core
{
    public class PagedList<T> : List<T>, IPagedList<T>
    {
        #region IPagedList implementions


        public int PageIndex
        {
            
            get;
            private set;
        }

        public int PageSize
        {
            get;
            private set;
        }

        public int TotalCount
        {
            get;
            private set;
        }

        public int TotalPages
        {
            get;
            private set;
        }

        public bool HasPreviousPage
        {
            get;
            private set;
        }

        public bool HasNextPage
        {
            get;
            private set;
        }

        #endregion

        #region Ctor
        private PagedList(int total, int pageSize, int pageIndex)
        {
            this.TotalCount = total;
            this.TotalPages = TotalCount / pageSize;
            if (TotalPages * pageSize < total)
                this.TotalPages++;
            this.PageSize = PageSize;
            this.PageIndex = pageIndex;
        }

        /// <summary>
        /// Ctor
        /// </summary>
        /// <param name="source">Source. Elements of current page will be added to the instance.</param>
        /// <param name="pageSize">Page size</param>
        /// <param name="pageIndex">page index</param>
        public PagedList(IQueryable<T> source, int pageSize, int pageIndex)
            : this(source.Count(), pageSize, pageIndex)
        {
            this.AddRange(source.Skip((pageIndex-1) * pageSize).Take(pageSize));
        }

        /// <summary>
        /// Ctor
        /// </summary>
        /// <param name="source">Source. All elements will be added to the instance</param>
        /// <param name="pageSize">Page size</param>
        /// <param name="pageIndex">Page index</param>
        public PagedList(IList<T> source, int pageSize, int pageIndex)
            : this(source.Count, pageSize, pageIndex)
        {
            this.AddRange(source);
        }
        /// <summary>
        /// Ctor
        /// </summary>
        /// <param name="source">Source.All elements will be added to the instance</param>
        /// <param name="pageSize">Page size</param>
        /// <param name="pageIndex">Page index</param>
        public PagedList(IEnumerable<T> source, int pageSize, int pageIndex)
            : this(source.Count(), pageSize, pageIndex)
        {
            this.AddRange(source);
        }
        #endregion
    }
}
